define(['table-col-collapse','api'],function (TableColCollapse,api) {
    var RoleManageModal = {
        name: 'role-manage-modal',
        template: ''
        + '<modal title="新增角色"'
        + 'v-model="insideShow"'
        + 'width="1010"'
        + 'ok-text="保存角色修改"'
        + 'on-cancel="cancel"'
        + ':mask-closable="false"'
        + '@on-ok="handleOk"'
        + '@on-cancel="handleCancel"'
        + 'class-name="addNewStaffWrap addRoleWrap vertical-center-modal">'
        + '<div class="addNewStaffBox clearfix" style="height: 560px">'
        + '<div class="leftInfo" style="width: 33.66% ;height:560px;position: relative">'
        + '<div class="roleTitle">角色</div>'
        + '<i-table border :columns="roleColumns" :data="tempUserTableData" @on-row-click="handleSelectItem" highlight-row></i-table>'
        + '</div>'
        + '<div class="limitItem"  style="float: right;width: 66.34%">'
        + '<div class="limitTitle">权限选项</div>'
        + '<i-table  border :columns="ruleColumns" :data="tableData" @on-select="handleSelectRuleRow" @on-select-cancel="handleSelectRuleRow"></i-table>'
        + '</div>'
        + '<button style="width:154px;height:24px;position: absolute;bottom: 0; left: 70px;margin-bottom: 10px" @click="handleAddUser">新增角色</button>'
        + '</div>'
        + '</modal>',
        components: {
            TableColCollapse: TableColCollapse
        },
        model: {
            prop: 'show',
            event: 'change-show'
        },
        props: {
            show: {
                type: Boolean,
                default: false
            }
        },
        watch: {
            show: function (val) {
                this.$data.insideShow = val;
            },
            insideShow: function (val) {
                this.$emit('change-show', val);
            }
        },
        data: function () {
            return {
                insideShow: this.show,
                tableData: [],
                userTableData: [],
                tempUserTableData: [],
                tempTableData: [],
                roleColumns: [],
                ruleColumns: [],
                tempSelectUser: {},
                postArr: [],
                tempPermissions: []
            }
        },
        methods: {
            handleOk: function () {
                var that = this;
                var arr = []
                // 判断用户是否添加新数据
                if (!(this.userTableData.length === this.tempUserTableData.length)) {
                    for (var i = this.userTableData.length; i < this.tempUserTableData.length; i++) {
                        this.postArr[this.tempUserTableData.length - i - 1] = this.tempUserTableData[i];
                        this.setRulesToUser(this.tempUserTableData.length - i - 1, this.tableData)
                        delete this.postArr[this.tempUserTableData.length - i - 1].userID
                    }
                }
                arr = this.isObjChange()
                if (arr.length > 0) this.postArr.push.apply(this.postArr, arr)

                // 过滤_highlight属性
                for (var i = 0; i < this.postArr.length; i++) {
                    delete this.postArr[i]._highlight;
                }

                if (this.postArr.length > 0) {
                    $.ajax({
                        type: 'post',
                        url: '/data/common/mock_post_ok.json',
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(this.postArr),
                        dataType: "json"
                    }).done(function (res) {
                        if (res.IsSuccess === true) {
                            that.$Message.success("保存成功");
                            that.$Modal.remove();
                        } else {
                            that.$Message.error("保存失败");
                        }
                    })
                }
            },
            isObjChange: function () {
                var editArr = []
                for (var i = 0; i < this.userTableData.length; i++) {
                    if (this.userTableData[i].name !== this.tempUserTableData[i].name ||
                        this.isJurisdictionList(this.userTableData[i].jurisdictionList, this.tempUserTableData[i].jurisdictionList)) {
                        editArr.push(this.tempUserTableData[i])
                    }
                }
                return editArr
            },
            isJurisdictionList: function (originalVal, newVal) {
                if (originalVal.length !== newVal.length) return true
                for (var i = 0; i < originalVal.length; i++) {
                    if (originalVal[i] !== newVal[i]) return true
                }
            },
            setRulesToUser: function (index, data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i]._checked && data[i].hasOwnProperty('parentNum')) {
                        if (this.postArr[index].jurisdictionList.indexOf(data[i].num) === -1) this.postArr[index].jurisdictionList.push(data[i].num)
                    }
                    var children = data[i].hasOwnProperty('children') && Array.isArray(data[i].children)
                        ? data[i].children
                        : false;
                    if (children) this.setRulesToUser(index, children);
                }
            },
            handleCancel: function () {
                if (!(this.userTableData.length === this.tempUserTableData.length)) {
                    this.tempUserTableData = this.userTableData.slice();
                }
            },
            handleAddUser: function () {
                var id = this.tempUserTableData.length + 1;

                this.tempUserTableData.push({
                    name: "",
                    userID: "" + id,
                    jurisdictionList: []
                });

                this.$nextTick(function () {
                    setTimeout(function () {

                        var obj = document.getElementById("user-role-id-" + id);
                        obj.removeAttribute('disabled');

                        obj.focus();
                    }, 0);
                });
            },
            handleSelectItem: function (row) {
                for (var i = 0; i < this.tempUserTableData.length; i++) {
                    if (this.tempUserTableData[i].userID === row.userID) this.tempSelectUser = this.tempUserTableData[i]
                }
                this.setRules(row, this.tableData);
                this.tableData = this.tableData.slice();
            },
            setRules: function (row, data) {
                // for (var i = 0; i < data.length; i++) {
                //     data[i]._checked = false;
                //     if (row.jurisdictionList.indexOf(data[i].num) !== -1) {
                //       data[i]._checked = true;
                //     }
                //
                //   var children = data[i].hasOwnProperty('children') && Array.isArray(data[i].children)
                //       ? data[i].children
                //       : false;
                //
                //   if (children) this.setRules(row, children);
                // }
                var flag = false;
                if (data.length) flag = true;
                for (var i = 0; i < data.length; i++) {
                    data[i]._checked = false;
                    if (row.jurisdictionList.indexOf(data[i].num) !== -1) {
                        data[i]._checked = true;
                    } else {
                        flag = false;
                    }

                    var children = data[i].hasOwnProperty('children') && Array.isArray(data[i].children)
                        ? data[i].children
                        : false;

                    if (children) {
                        var resFlag = this.setRules(row, children);
                        if (!data[i]._checked) data[i]._checked = resFlag;
                        console.log(resFlag);
                    }
                }
                return flag;
            },
            // 数据初始化
            initData: function () {
                var that = this
                api.GetAllPermissions()
                    .done(function (res) {
                        if (res.IsSuccess === true) {
                            that.tableData = res.ResultObject
                        }
                    })
                $.getJSON("/data/system/mock_user_list.json")
                    .done(function (res) {
                        if (res.IsSuccess === true) {
                            that.userTableData = res.ResultObject;
                            that.tempUserTableData = JSON.parse(JSON.stringify(res.ResultObject));
                        }
                    })
            },
            initColumns: function () {
                var that = this;
                this.roleColumns = [
                    {
                        title: '角色名称',
                        width: 200,
                        key: 'name',
                        render: function (h, params) {
                            return h('div', [
                                h('input', {
                                    attrs: {
                                        id: "user-role-id-" + params.row.userID,
                                        type: "text",
                                        value: params.row.name,
                                        disabled: "disabled"
                                    },
                                    style: {
                                        width: "100%",
                                        background: "none",
                                        outline: "none",
                                        border: "0"
                                    },
                                    on: {
                                        blur: function () {
                                            var obj = document.getElementById("user-role-id-" + params.row.userID);
                                            if (obj.value === params.row.name) {
                                                obj.setAttribute('disabled', 'true');
                                            } else {
                                                that.tempUserTableData[params.index].name = obj.value;
                                                obj.setAttribute('disabled', 'true');
                                            }
                                        }
                                    }
                                })
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'operation',
                        align: 'center',
                        render: function (h, params) {
                            return h('div', [
                                h('span', {
                                    style: {
                                        display: 'inline-block',
                                        width: '14px',
                                        height: '14px',
                                        'background-image': 'url(/components/role-manage-modal/update.png)'
                                    },
                                    on: {
                                        click: function () {
                                            var obj = document.getElementById("user-role-id-" + params.row.userID);
                                            obj.removeAttribute('disabled');
                                            obj.focus();
                                        }
                                    }
                                }), h('span', {
                                    style: {
                                        display: 'inline-block',
                                        width: '14px',
                                        height: '14px',
                                        margin: '0 7px 0 7px',
                                        'background-image': 'url(/components/role-manage-modal/copy.png)'
                                    },
                                    on: {
                                        click: function () {
                                            that.tempUserTableData.splice(params.index, 0, params.row)
                                            that.tempUserTableData[params.index + 1].userID = that.tempUserTableData.length
                                        }
                                    }
                                }), h('span', {
                                    style: {
                                        display: 'inline-block',
                                        width: '14px',
                                        height: '14px',
                                        'background-image': 'url(/components/role-manage-modal/del.png)'
                                    },
                                    on: {
                                        click: function () {
                                            that.tempUserTableData.splice(params.index, 1)
                                        }
                                    }
                                })
                            ]);
                        }
                    }
                ];
                this.ruleColumns = [
                    {
                        type: 'selection',
                        width: 50,
                        align: 'center'
                    },
                    {
                        title: '权限菜单',
                        key: 'content',
                        render: function (h, params) {
                            return h(TableColCollapse, {
                                props: {
                                    params: params,
                                    tableData: that.tableData,
                                    equalsKey: 'num'
                                },
                                on: {
                                    'table-data-change': function (newData) {
                                        that.tableData = newData;
                                    }
                                }
                            }, [
                                h('span', params.row.content)
                            ]);
                        }
                    }
                ]
            },
            handleSelectRuleRow: function (selection, row) {
                var that = this;
                if (row.hasOwnProperty('children') && row.children.length) {
                    row._checked = !row._checked;
                    row.children.forEach(function (item) {
                        item._checked = row._checked;
                    });

                    this.tableData.forEach(function (item, index, input) {
                        if (item.num === row.num) {
                            input[index] = row;
                            if (item.isCollapse) {
                                that.tableData.forEach(function (item) {
                                    if (item.parentNum === row.num) item._checked = row._checked;
                                });
                            }
                        }
                    });

                } else {
                    var flagCheckedAll = true;
                    var parentIndex = -1;
                    this.tableData.forEach(function (item, index) {
                        if (row.parentNum === item.num && parentIndex === -1) parentIndex = index;
                        if (item.num === row.num) item._checked = !item._checked;
                        if ((row.parentNum === item.parentNum) && !item._checked) flagCheckedAll = false;
                    });
                    this.tableData[parentIndex]._checked = flagCheckedAll;
                }

                // 深拷贝更新iview表格
                this.tableData = this.tableData.slice();
                this.tempPermissions = []
                this.handleSetPermissions(this.tableData)
                this.tempUserTableData[this.tempUserTableData.indexOf(this.tempSelectUser)].jurisdictionList = this.tempPermissions
                // clear highlight
                for (var i = 0; i < this.tempUserTableData.length; i++) {
                    this.tempUserTableData[i]._highlight = false;
                }
                this.tempUserTableData[this.tempUserTableData.indexOf(this.tempSelectUser)]._highlight = true
            },
            handleSetPermissions: function (data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].parentNum !== "-1" && data[i]._checked && this.tempPermissions.indexOf(data[i].num) === -1) this.tempPermissions.push(data[i].num)
                    var children = data[i].hasOwnProperty('children') && Array.isArray(data[i].children)
                        ? data[i].children
                        : false;
                    if (children) this.handleSetPermissions(children);
                }
            }
        },
        created: function () {
            this.initData()
            this.initColumns()
        }
    }
    return RoleManageModal
})
